package org.my.stock.h2;

import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.my.stock.util.BrotliHttpClientHelper;
import org.my.stock.util.MyUtil;

import java.beans.PropertyVetoException;
import java.sql.*;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TypeToStockH2 {
    public static String getUrl(String typeSymbol, int index) {
        return "https://push2.eastmoney.com/api/qt/clist/get?cb=jQuery112304073647533562328_1745155685082&fid=f62&po=1&pz=50&pn="+ index +"&np=1&fltt=2&invt=2&ut=8dec03ba335b81bf4ebdf7b29ec27d15&fs=b%3A" + typeSymbol + "&fields=f12%2Cf14%2Cf2%2Cf3%2Cf62%2Cf184%2Cf66%2Cf69%2Cf72%2Cf75%2Cf78%2Cf81%2Cf84%2Cf87%2Cf204%2Cf205%2Cf124%2Cf1%2Cf13";
    }

    public static void updateAll() throws SQLException, ClassNotFoundException, PropertyVetoException {
        //String springCfgPath = "/Users/chenfei/Documents/Java/my_database/my-stock/src/main/resources/default-config.xml";
        Connection conn = MyUtil.getConnection();

        String sql = "SELECT code, name FROM stock_type";
        PreparedStatement stmt = conn.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            getData(conn, rs.getString(1), rs.getString(2), 1);
        }

        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
        if (conn != null) conn.close();
    }

    public static void getData(Connection conn, String typeSymbol, String typeName, int index) {
        String url = getUrl(typeSymbol, index);
        if (url != null) {
            HttpClient httpClient = BrotliHttpClientHelper.createBrotliClient();

            try {
                // 1. 创建 GET 请求
                HttpGet request = new HttpGet(url);

                // 2. 设置请求头（防止被服务器拒绝）
                request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
                request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
                request.setHeader("Accept-Encoding", "gzip, deflate, br");
                request.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
                request.setHeader("Cache-Control", "max-age=0");
                request.setHeader("Connection", "keep-alive");
                request.setHeader("Cookie", "em_hq_fls=js; intellpositionL=1140px; em-quote-version=topspeed; intellpositionT=1298px; qgqp_b_id=e04e31a1e6446068e54e0f7808401919; sid=142772185; mtp=1; ct=oFv-pht6ZiYeFSXV2tPdRfkJ0x6ZftJa4X2TKji2eXO0Pl_YBbWxGBEwUTJ4z6N0GPPyYYrAizsB50OwF5PQc3x4HESZOAriGonI9ewh-RikgY0SEGHZcdA5RKg5RB4dPVIr3TCQLKkZkYOXQKFQElZVysNazqJ5O7csdsQO8U8; ut=FobyicMgeV5FJnFT189SwH2JOfiEw7mPz0LG7-oku6sFYOCxdbsEi2cnDTMMTwLC08VTgq_y28iF-S7gffFe0HKuLD1gS302VWRzT3pl7pFn5lPVWP0FGEkMzX3xkH4zZ26gwPXYW-E0EBZ8yNwMjA61nTdT3wPUm2MO4K_-pv5FU7C4OKwrxdk0UuppgrEnJEgArYW9ONwiZM25_K7mvoROgdu_rvCGeunwxnPYxpGqdl5zugvVg1iYtj7NhgcPysSINh74Fg1SOz2r1EMofNQ2h17qfzYUEa1h5_9kJkiB1FoE_P6A7kqYkMsr92-xF4fQoC_luUS273FRQNpqdmsbdOgZn9GV; pi=5274385825271944%3Bc5274385825271944%3B%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90%3BdCmpCdx6Fv0K9ySmGo1L60bQl9guPYNF9kW50ggeyA%2BOOeqCGeepIZPP0w088pbSCmH3QEBcYqyucZR9kKKJ4yNWHFBnnJznMgN%2F0PAMxp8Q%2FuJWZ89w97SHWrysOsb%2B93O45rM%2BhQroFhMO0X604MpHaHC%2F9yVsQmkbCVr5W1pviVaJGTOj%2FDWWzVmDAqUqGJzUNqW2%3BYeT6DxMds0uwdT3PftF0xut%2B1faguRkAY5Rpcphp0hhNyyGaYsTQbiMZEJxNWp7SrYuMigne0BGrZhWVS5SuyPZkN9SQHEd8yzBJUAbFcxV2So8rHP9l%2FY1Cf50pniZsBXw%2Bk0GvzjRxxPfbt9j1Vj8dTOWabw%3D%3D; vtpst=%7C; uidal=5274385825271944%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90; fullscreengg=1; fullscreengg2=1; st_si=66098437338071; emshistory=%5B%22%E6%BD%9E%E5%AE%89%E7%8E%AF%E8%83%BD%22%2C%22undefined%22%5D; HAList=ty-0-000893-%u4E9A%u94BE%u56FD%u9645%2Cty-90-BK0712-%u4E00%u5E26%u4E00%u8DEF%2Cty-1-600171-%u4E0A%u6D77%u8D1D%u5CAD%2Cty-90-BK0854-%u534E%u4E3A%u6982%u5FF5%2Cty-1-601398-%u5DE5%u5546%u94F6%u884C%2Cty-90-BK0968-%u56FA%u6001%u7535%u6C60%2Cty-0-300661-%u5723%u90A6%u80A1%u4EFD%2Cty-90-BK0638-%u521B%u4E1A%u6210%u4EFD%2Cty-1-601699-%u6F5E%u5B89%u73AF%u80FD%2Cty-0-300782-%u5353%u80DC%u5FAE; st_pvi=18633756697256; st_sp=2021-05-13%2015%3A20%3A17; st_inirUrl=https%3A%2F%2Fcn.bing.com%2F; st_sn=96; st_psi=2025041315314915-113300300815-4079987765; st_asi=delete");
                request.setHeader("Host", "push2his.eastmoney.com");
                request.setHeader("Sec-Fetch-Dest", "document");
                request.setHeader("Sec-Fetch-Mode", "navigate");
                request.setHeader("Upgrade-Insecure-Requests", "1");

                // 3. 执行请求并获取响应
                HttpResponse response = httpClient.execute(request);

                // 4. 检查状态码
                //int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("所属类型: " + typeName);

                // 5. 读取响应内容
                HttpEntity entity = response.getEntity();
                if (entity != null) {

                    // 关键：使用 UTF-8 编码转换解压后的字节流
                    String content = EntityUtils.toString(entity, "UTF-8");
                    //toDb(ignite, cache, content, type_name, day);
                    //toDb(cache, content, symbol);
                    toDb(conn, content, typeName, typeSymbol, index);
                    System.out.println("解码内容:\n" + content);
                }

            } catch (Exception e) {
                System.err.println("请求失败: " + e.getMessage());
            } finally {
                // 6. 释放连接（重要！）
                httpClient.getConnectionManager().shutdown();
            }
        }
    }

    public static void toDb(Connection conn, final String line, final String typeName, final String typeSymbol, final int index) throws SQLException {
        Pattern pattern = Pattern.compile("\\(([^)]+)\\)");
        Matcher matcher = pattern.matcher(line);

        if (matcher.find()) {
            String result = matcher.group(1); // 获取第一个捕获组内容

            LinkedTreeMap m = MyUtil.getGson().fromJson(result, new TypeToken<LinkedTreeMap>() {
            }.getType());
            LinkedTreeMap data = (LinkedTreeMap) m.get("data");
            List<LinkedTreeMap> diff = (List<LinkedTreeMap>) data.get("diff");
            Double t1 = Double.valueOf(data.get("total").toString());
            int total = t1.intValue();
            try {

                for (LinkedTreeMap tm : diff) {
                    // 股票编号
                    String f12 = (String) tm.get("f12");
                    // 股票名字
                    String f14 = (String) tm.get("f14");

                    if (getSymbolCount(conn, f12, typeName) == 0L) {
                        String sql = "insert into type_stock (symbol, name, type_name) values ('" + f12 + "', '" + f14 + "', '" + typeName + "')";
                        //cache.query(new SqlFieldsQuery(sql)).getAll();
                        PreparedStatement st = conn.prepareStatement(sql);
                        st.executeUpdate();

                        st.close();
                    }
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

            if (index * 50 < total) {
                getData(conn, typeSymbol, typeName, index + 1);
            }
        }
    }

    public static Long getSymbolCount(Connection conn, String symbol, String type_name) {
        String sql = "select count(*) from type_stock where symbol = '"+ symbol +"' and type_name = '"+ type_name +"'";

        PreparedStatement stmt = null;
        ResultSet rs = null;
        long id = 0L;

        try {
            stmt = conn.prepareStatement(sql);

            // 5. 执行查询并获取结果集
            rs = stmt.executeQuery();

            // 6. 遍历结果集并处理数据
            while (rs.next()) {
                id = rs.getLong(1);
            }

        } catch (SQLException e) {
            System.err.println("数据库操作失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. 关闭资源（反向顺序）
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return id;
    }
}
